﻿using Microsoft.Extensions.DependencyModel;
using System.Reflection;
using System.Runtime.Loader;
using WomanMotion.WebApi.Infrastructure.Ioc;

namespace WomanMotion.WebApi.Api.Utility
{
    /// <summary>
    /// 批量注册依赖注入的接口和类
    /// </summary>
    public static class ServiceCollectionExtension
    {
        public static IServiceCollection AutoScrutor(this IServiceCollection services)
        {
            //获取整个解决方案的程序集
            services.Scan(x =>
            {
                List<Assembly> assemblyList = new List<Assembly>();
                DependencyContext dependencyContext = DependencyContext.Default;

                dependencyContext.CompileLibraries.Where(lib => !lib.Serviceable && lib.Type != "package")
                    .ToList().ForEach(item =>
                    {
                        if (item.Type == "project")//(item.Name.Contains("MES"))
                        {
                            Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(item.Name));
                            assemblyList.Add(assembly);
                        }
                    });
                assemblyList = assemblyList
                            .Where(x => x.FullName.StartsWith("WomanMotion.")).ToList();

                x.FromAssemblies(assemblyList)
                 .AddClasses(classes => classes.AssignableTo<ISingletonDependency>()).AsImplementedInterfaces().WithSingletonLifetime()
                 .AddClasses(classes => classes.AssignableTo<IScopedDependency>()).AsImplementedInterfaces().WithScopedLifetime()
                 .AddClasses(classes => classes.AssignableTo<ITransientDependency>()).AsImplementedInterfaces().WithTransientLifetime();
            });
            return services;
        }
    }
}
